#!/usr/bin/env python3
# auto_refresh_global_dashboard_robust.py

import time
import argparse
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import WebDriverException, NoSuchWindowException

def find_fullscreen_button(driver):
    """Finds the fullscreen button using exact text match (from your HTML)"""
    # We'll use the most reliable selector: button containing text "Fullscreen"
    selectors = [
        # 1. XPath: Find button containing exact text "Fullscreen"
        '//button[contains(., "Fullscreen")]',
        # 2. CSS: Button with class "ant-btn" (common in Ant Design UIs)
        "button.ant-btn",
    ]

    for selector in selectors:
        try:
            if selector.startswith("//"):
                button = WebDriverWait(driver, 10).until(
                    EC.element_to_be_clickable((By.XPATH, selector))
                )
            else:
                button = WebDriverWait(driver, 10).until(
                    EC.element_to_be_clickable((By.CSS_SELECTOR, selector))
                )
            return button
        except:
            continue
    raise Exception("Fullscreen button not found! Check HTML structure.")

def is_browser_alive(driver):
    """Checks if the browser window is still open and responsive."""
    try:
        # Get the current window handle. This will throw an exception if the window is closed.
        driver.current_window_handle
        return True
    except (NoSuchWindowException, WebDriverException):
        return False

def setup_driver():
    """Sets up and returns a new WebDriver instance."""
    chrome_options = Options()
    # chrome_options.add_argument("--start-maximized")
    chrome_options.add_argument("--disable-infobars")
    chrome_options.add_argument("--no-first-run")
    chrome_options.add_argument("--disable-extensions")
    chrome_options.add_argument("--no-sandbox")
    chrome_options.add_argument("--disable-dev-shm-usage")
    chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"])
    # Consider adding this option to prevent immediate closure on script end (though not the main solution)
    # chrome_options.add_experimental_option("detach", True)

    return webdriver.Chrome(options=chrome_options)

def main():
    # ... (Argument parsing code remains the same)
    DEFAULT_URL = "http://192.168.10.66/camera_monitor"
    DEFAULT_INTERVAL = 600  # 10 minutes

    parser = argparse.ArgumentParser(description='Automatically refresh and fullscreen a dashboard.')
    parser.add_argument('--url', default=DEFAULT_URL,
                       help=f'URL of the dashboard to refresh (default: {DEFAULT_URL})')
    parser.add_argument('--interval', type=int, default=DEFAULT_INTERVAL,
                       help=f'Refresh interval in seconds (default: {DEFAULT_INTERVAL} seconds)')
    args = parser.parse_args()

    driver = None

    try:
        while True:
            # Step 1: Create or Recreate the browser instance
            if driver is None or not is_browser_alive(driver):
                print("\n" + "="*50)
                print("Initializing or Re-initializing Browser...")
                if driver is not None:
                    # If driver exists but browser is dead, quit the old driver session properly
                    try:
                        driver.quit()
                    except:
                        pass
                driver = setup_driver()
                print("Browser is ready.")

            # Step 2: Perform the dashboard refresh routine
            try:
                print(f"\nRefreshing at {time.strftime('%H:%M:%S')}")
                driver.get(args.url)
                print(f"Page refreshed (URL: {args.url})")
                time.sleep(6)

                driver.fullscreen_window()
                time.sleep(3)

                fullscreen_button = find_fullscreen_button(driver)
                fullscreen_button.click()
                print("Entered Fullscreen mode.")

                # Step 3: Wait, but check periodically if the browser is still alive
                wait_remaining = args.interval
                while wait_remaining > 0:
                    time.sleep(10)  # Check every 10 seconds
                    wait_remaining -= 10
                    if not is_browser_alive(driver):
                        print("Browser was closed during wait. Will restart on next cycle.")
                        break  # Break out of the waiting loop to restart the browser

            except (WebDriverException, Exception) as e:
                # Handle any errors during the refresh routine (e.g., network issues, element not found)
                print(f"An error occurred during the refresh cycle: {str(e)}")
                print("The browser session may be invalid. It will be recreated.")
                try:
                    driver.quit()
                except:
                    pass
                driver = None  # Force recreation of driver in the next cycle
                # Optional: Wait a bit before retrying to avoid rapid failure loops
                time.sleep(30)

    except KeyboardInterrupt:
        print("\nScript stopped by user.")
    finally:
        if driver is not None:
            try:
                driver.quit()
                print("Browser closed successfully.")
            except:
                pass

if __name__ == "__main__":
    main()